package com.dys.test13;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @className: com.dys.test13.LockTest
 * @description: com.dys.test13
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/08/19 下午10:27
 */
public class LockTest implements Runnable {
    int ticketNum = 10;
    // 拿来一把锁
    Lock lock = new ReentrantLock();// 多态：接口=实现类

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                // 打开锁
                lock.lock();
                if (ticketNum > 0) {
                    System.out.println("我在" + Thread.currentThread().getName() + "，购买了从【深圳->贵阳】的第" + ticketNum-- + "张票");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭锁：即使有异常，这个锁也可以得到释放
                lock.unlock();
            }
        }
    }
}
